import { defineStore } from 'pinia'

export const useChatStore = defineStore('chat', {
  state: () => ({
    chatHistory: [],
    currentChatIndex: -1,
    currentMessages: []
  }),
  
  getters: {
    getChatHistory: (state) => state.chatHistory,
    getCurrentChat: (state) => state.currentChatIndex >= 0 ? state.chatHistory[state.currentChatIndex] : null,
    getCurrentMessages: (state) => state.currentMessages
  },
  
  actions: {
    addChat(title) {
      const newChat = {
        id: Date.now(),
        title,
        messages: [],
        createdAt: new Date().toISOString()
      }
      
      this.chatHistory.unshift(newChat)
      this.currentChatIndex = 0
      this.currentMessages = []
      
      return newChat
    },
    
    setCurrentChat(index) {
      if (index >= 0 && index < this.chatHistory.length) {
        this.currentChatIndex = index
        this.currentMessages = [...this.chatHistory[index].messages]
        return true
      }
      return false
    },
    
    addMessage(message) {
      if (this.currentChatIndex >= 0) {
        this.chatHistory[this.currentChatIndex].messages.push(message)
        this.currentMessages.push(message)
        return true
      }
      return false
    },
    
    updateChatTitle(index, title) {
      if (index >= 0 && index < this.chatHistory.length) {
        this.chatHistory[index].title = title
        return true
      }
      return false
    },
    
    deleteChat(index) {
      if (index >= 0 && index < this.chatHistory.length) {
        this.chatHistory.splice(index, 1)
        
        if (this.currentChatIndex === index) {
          this.currentChatIndex = this.chatHistory.length > 0 ? 0 : -1
          this.currentMessages = this.currentChatIndex >= 0 ? [...this.chatHistory[this.currentChatIndex].messages] : []
        } else if (this.currentChatIndex > index) {
          this.currentChatIndex--
        }
        
        return true
      }
      return false
    },
    
    clearAllChats() {
      this.chatHistory = []
      this.currentChatIndex = -1
      this.currentMessages = []
    }
  },
  
  persist: {
    key: 'chat-store',
    storage: localStorage,
  },
})
